package com.engine.cn.leetcode.link;

/**
 * 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
 * 翻转链表，双指针pre,next;中间夹着head
 */
public class ReverseLinkedList {
    public static Node reverseList(Node head) {
        Node pre = null;
        Node next;
        while (head != null) {
            //记录head的下一个位置，主要为了方便head能来到next的位置
            next = head.next;
            //把head的next先翻转过来
            head.next = pre;
            //pre往前移，来到head的位置
            pre = head;
            //head来到next的位置
            head = next;
        }

        return pre;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        Node reversed = reverseList(head);
        System.out.println("反转后==>" + reversed.val + "," + reversed.next.val + "," + reversed.next.next.val);
    }
}
